<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('./import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ hiretypeformat(row.formOfEmployment
              ) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hassroles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增弹层 -->
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        @close="hCloseDialog"
      >
        <emp-dialog ref="AddEmployee" @success="hsuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role
          v-if="showDialogRole"
          :rolse-id="rolseId"
          @close="showDialogRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignRole from './assignRole.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
// import { delEmployee } from '@/api/employees'
// [{id:1,value:'正式}，{id:2,value:'非正式}] =>>{1:正式，2：非正式}
// 方法一把数组对象转为 对象
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// 方法二 高阶函数reduce
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: { empDialog, assignRole },
  data() {
    return {
      rolseId: '',
      showDialogRole: false, // 分配权限的弹层
      showDialog: false,
      list: [],
      page: 1,
      size: 2,
      total: 0
    }
  },
  created() {
    this.loadgetEmployee()
  },
  methods: {
    hassroles(id) {
      this.rolseId = id
      this.showDialogRole = true
    },
    // 英文的key转成中文
    dataForm(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1 获取表头
      const one = list[0]
      let header = []
      if (one) {
        header = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2 将每一个对象中的值存储到数组中 将每个数组存储到大数组
      const data = list.map(item => {
        return Object.values(item)
      })
      console.log(header)
      console.log(data)
      return { header, data }
    },
    async handleDownload() {
      // 1 发送请求 拿到数据
      try {
        const res = await getEmployee(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows, 'res.data.rows')
        // 2 将获取的数据转换成excel 格式  header data
        const { header, data } = this.dataForm(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          // const tHeader = ['姓名', '年龄']
          // const data = [['曹操', 40], ['刘备', 45]]
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    hdel(id) {
      this.$confirm('删除').then(async() => {
        const res = await delEmployee(id)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadgetEmployee()
        console.log(res)
      }).catch(err => err)
    },
    hCloseDialog() {
      // 相当于是在父组件中去执行子组件中方法
      // 去清空 子组件中的表单数据和校验结果
      // 子组件.resetForm()
      // console.log('在父组件中获取子组件的引用', this.$refs.AddEmployee)
      this.$refs.AddEmployee.resetForm()
    },
    hsuccess() {
      // 获取最大页码值
      this.total++
      const maxpage = Math.ceil(this.total / this.size)
      this.page = maxpage
      this.loadgetEmployee()
      this.showDialog = false
    },
    // 每页条数的控制
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadgetEmployee()
    },
    // 页码值的切换
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadgetEmployee()
    },
    hiretypeformat(data) {
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 实现获取员工列表
    async loadgetEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        if (res.code === 10000) {
          console.log(res.data)
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    }
  }

}

</script>
